<script setup>
import { useMonacoEditor } from '@/hooks';
import { onMounted, computed, watch } from 'vue';

// const props = defineProps({
//   width: '100%',
//   height: '100%',
//   language: 'javascript',
//   editorOption: () => ({}),
//   modelValue: '',
// });
const props = defineProps({
  width: {
    type: String,
    default: '100%'
  },
  height: {
    type: String,
    default: '100%'
  },
  language: {
    type: String,
    default: 'javascript'
  },
  editorOption: {
    type: Object,
    default: () => ({}),
  },
  modelValue: {
    type: String,
    default: ''
  },
});

const emits = defineEmits(['update:modelValue']);

const monacoEditorStyle = computed(() => {
  return {
    width: typeof props.width === 'string' ? props.width : props.width + 'px',
    height:
      typeof props.height === 'string' ? props.height : props.height + 'px',
  };
});

const { monacoEditorRef, createEditor, updateVal, updateOptions, getEditor } =
  useMonacoEditor(props.language);

onMounted(() => {
  const monacoEditor = createEditor(props.editorOption);
  updateMonacoVal(props.modelValue);
  monacoEditor?.onDidChangeModelContent(() => {
    emits('update:modelValue', monacoEditor?.getValue());
  });
});

watch(
  () => props.modelValue,
  () => {
    updateMonacoVal(props.modelValue);
  }
);

function updateMonacoVal(val) {
  if (val !== getEditor()?.getValue()) {
    updateVal(val);
  }
}

defineExpose({ updateOptions });
</script>

<template>
  <div ref="monacoEditorRef" :style="monacoEditorStyle"></div>
</template>
